package com.qdu.servlet;

import com.qdu.entity.Admin;
import com.qdu.entity.User;
import com.qdu.util.DatabaseUtil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 该Servlet负责处理添加新学生的请求
 *
 * @author Anna
 */
@WebServlet("/a_ass")
public class Admin_AddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取新注册的学生的信息，封装成一个学生对象
        req.setCharacterEncoding("utf-8");

        //获取学生的5项信息，封装成一个Student对象
        User newUser = new User(null, req.getParameter("Uname"), req.getParameter("Upwd"), req.getParameter("Uemail"));
        Admin newAdmin = new Admin(req.getParameter("Uname"), req.getParameter("Upwd"));
        //2. 执行业务逻辑
        //将新学生插入数据库
//        String driver_class = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//        String url = "jdbc:sqlserver://localhost:1433;databaseName=Crp";
//        String username = "sa";
//        String password = "sa";

        Connection con = null;
        PreparedStatement ps = null;
        int rows = 0; //受影响行数
        try {
//            Class.forName(driver_class);
//            con = DriverManager.getConnection(url, username, password);
            con = DatabaseUtil.getConnection();
            if (req.getParameter("optins").equals("User")) {
                ps = con.prepareStatement("INSERT INTO [dbo].[User] ( [Uname], [Upwd],[Uemail]) values(?,?,?)");
                ps.setString(1, newUser.getUname());
                ps.setString(2, newUser.getUpwd());
                ps.setString(3, newUser.getUemail());
                rows = ps.executeUpdate();
            } else {
                ps = con.prepareStatement("INSERT INTO [dbo].[Admin] ( [Aname], [Apwd]) values(?,?)");
                ps.setString(1, newAdmin.getAneme());
                ps.setString(2, newAdmin.getApwd());
                rows = ps.executeUpdate();
            }

        } catch (Exception e) { 
            e.printStackTrace();
        } finally {
            try {
                if (null != ps) {
                    ps.close();
                }
                if (null != con) {
                    con.close();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        //3. 生成响应内容，这里直接返回了受影响的行数，用于判断是否插入成功
        resp.getWriter().println(rows);
    }
}
